<template>
  <el-select
    ref="selectTree"
    v-model="valueName"
    :clearable="clearable"
    @clear="clearHandle"
    @change="changeValue"
    style="width: 100%;"
    size="mini"
  >
    <el-option :value="valueName" class="options">
      <el-tree
        id="tree-option"
        ref="selectTree"
        :accordion="accordion"
        :data="options"
        :props="props"
        ::default-expanded-keys="[value]"
        :node-key="props.value"
        @node-click="handleNodeClick"
        :expand-on-click-node="!checkStrictly">
        <span slot-scope="{ data }">
          <i :class="[data.color != null ? 'ification_col' : '']" :style="{ 'background-color': data.color }"></i>
          {{ data[props.label] }}
        </span>
      </el-tree>
    </el-option>
  </el-select>
</template>

<script>
import { tree } from '@/api/partyMemberManagement/organizationalInformationManagement.js'

export default {
  name: 'ClassifyTreeSelect',
  props: {
    // 配置项
    props: {
      type: Object,
      default: () => {
        return {
          children: 'orgInfoMgmtQueryTreeVOList',
          label: 'fullNamePartyOrg',
          value: 'id'
        }
      }
    },
    // 初始值（单选）
    value: {
      type: Number,
      default: null
    },
    // 可清空选项
    clearable: {
      type: Boolean,
      default: true
    },
    // 自动收起
    accordion: {
      type: Boolean,
      default: false
    },
    // 是否可选任意一级
    checkStrictly: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      options: [],
      resultValue: [], // 传给父组件的数组对象值
      valueName: '' // 输入框显示值
    }
  },
  watch: {
    value () {
      this.initHandle()
    }
  },
  mounted () {
    this.getData()
  },
  methods: {
    getData () {
      tree().then(({ code, data }) => {
        if (code === 'success') {
          this.options = data
          this.initHandle()
        }
      })
    },

    // 初始化显示
    initHandle () {
      const resultValue = this.findParentIdsById(this.value, this.options)
      if (resultValue) {
        // 单选
        this.valueName = resultValue[this.props.label]
      }
      this.initScroll()
    },

    findParentIdsById (id, data, parentIds = []) {
      console.log(id, data)
      for (let i = 0; i < data.length; i++) {
        if (data[i][this.props.value] === id) {
          console.log(data[i])
          return data[i]
        } else if (data[i].orgInfoMgmtQueryTreeVOList) {
          const result = this.findParentIdsById(id, data[i].orgInfoMgmtQueryTreeVOList, [...parentIds, data[i].id])
          if (result) {
            return result
          }
        }
      }
      return null
    },

    // 初始化滚动条
    initScroll () {
      this.$nextTick(() => {
        const scrollWrap = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')[0]
        const scrollBar = document.querySelectorAll('.el-scrollbar .el-scrollbar__bar')
        scrollWrap.style.cssText = 'margin: 0px; max-height: none; overflow: hidden;'
        scrollBar.forEach(ele => { ele.style.width = 0 })
      })
    },
    // 切换选项
    handleNodeClick (node) {
      if (this.checkStrictly) {
        this.$refs.selectTree.blur()
        this.valueName = node[this.props.label]
        this.resultValue = node
        this.$emit('getValue', this.resultValue)
        this.$emit('input', this.resultValue[this.props.value])
      } else {
        // 设置点击叶子节点后被选中 可以更改为点击父节点也生效
        // eslint-disable-next-line eqeqeq
        if (node.children == null || node.children == undefined) {
          // 单选
          this.$refs.selectTree.blur()
          this.valueName = node[this.props.label]
          this.resultValue = node
          this.$emit('getValue', this.resultValue)
          this.$emit('input', this.resultValue[this.props.value])
        }
      }
    },
    // 从输入框中直接删除某个值时
    changeValue (val) {
      // 单选
      this.$emit('getValue', val)
    },
    // 清除选中
    clearHandle () {
      this.valueName = ''
      this.resultValue = []
      this.clearSelected()
      this.$emit('getValue', this.resultValue)
      this.$emit('input', '')
    },
    // 清空选中样式
    clearSelected () {
      const allNode = document.querySelectorAll('#tree-option .el-tree-node')
      allNode.forEach((element) => element.classList.remove('is-current'))
    }
  }
}
</script>
<style scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
}

.el-select-dropdown__item.selected {
  font-weight: normal;
}

.el-tree {
  padding: 0 10px;
}

ul li>>>.el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}

.el-tree-node__label {
  font-weight: normal;
}

.el-tree>>>.is-current .el-tree-node__label {
  color: #409EFF;
  font-weight: 700;
}

.el-tree>>>.is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}

.el-popper {
  z-index: 9999;
}

.ification_col {
  width: 20px;
  height: 10px;
  display: inline-block;
}
</style>
